package org.example.controller;

import org.example.service.DataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 性能监控控制器
 */
@RestController
@RequestMapping("/api/performance")
public class PerformanceController {
    
    @Autowired
    private DataService dataService;
    
    /**
     * 生成数据并返回性能统计
     */
    @PostMapping("/generate-with-stats")
    public Map<String, Object> generateDataWithStats() {
        Map<String, Object> result = new HashMap<>();
        
        long startTime = System.currentTimeMillis();
        
        try {
            dataService.generateAndInsertData();
            
            long endTime = System.currentTimeMillis();
            long totalTime = endTime - startTime;
            
            result.put("success", true);
            result.put("message", "数据生成成功");
            result.put("totalTime", totalTime + "ms");
            result.put("totalTimeSeconds", totalTime / 1000.0 + "s");
            
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            long totalTime = endTime - startTime;
            
            result.put("success", false);
            result.put("message", "数据生成失败: " + e.getMessage());
            result.put("totalTime", totalTime + "ms");
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取系统信息
     */
    @GetMapping("/system-info")
    public Map<String, Object> getSystemInfo() {
        Map<String, Object> systemInfo = new HashMap<>();
        
        Runtime runtime = Runtime.getRuntime();
        
        systemInfo.put("availableProcessors", runtime.availableProcessors());
        systemInfo.put("totalMemory", runtime.totalMemory() / 1024 / 1024 + "MB");
        systemInfo.put("freeMemory", runtime.freeMemory() / 1024 / 1024 + "MB");
        systemInfo.put("maxMemory", runtime.maxMemory() / 1024 / 1024 + "MB");
        systemInfo.put("usedMemory", (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024 + "MB");
        
        return systemInfo;
    }
}

